// frontend/src/store/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '../utils/request' // P4 导入的 Axios
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 1. State: 尝试从 localStorage 恢复 Token
  const token = ref(localStorage.getItem('token') || null)
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || null)

  // 2. Getters
  const isLoggedIn = ref(!!token.value)

  // 3. Actions

  // 设置 Token 和 UserInfo (内部使用)
  function _setAuth(data) {
    token.value = data.token
    userInfo.value = data.user
    isLoggedIn.value = true
    localStorage.setItem('token', data.token)
    localStorage.setItem('userInfo', JSON.stringify(data.user))
  }

  // 清空 Token 和 UserInfo (内部使用)
  function _clearAuth() {
    token.value = null
    userInfo.value = null
    isLoggedIn.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 登录 (P5 调用 P2 的 API)
  const login = async (username, password) => {
    try {
      const res = await request.post('/login', { username, password })
      if (res.data.success) {
        _setAuth(res.data)
        ElMessage.success(res.data.message)
        return true
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '登录失败')
      return false
    }
  }

  // 注册 (P5 调用 P2 的 API)
  const register = async (username, password, email) => {
     try {
      const res = await request.post('/register', { username, password, email })
      if (res.data.success) {
        ElMessage.success(res.data.message)
        return true
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '注册失败')
      return false
    }
  }

  // 更新用户信息
  const updateProfile = async (profileData) => {
    try {
      // 这里应该调用后端API更新用户信息
      // const res = await request.put('/profile', profileData)
      
      // 模拟API调用成功
      const updatedUser = { ...userInfo.value, ...profileData }
      userInfo.value = updatedUser
      localStorage.setItem('userInfo', JSON.stringify(updatedUser))
      
      ElMessage.success('个人信息更新成功')
      return true
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '更新失败')
      return false
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    try {
      // 这里应该调用后端API修改密码
      // const res = await request.put('/change-password', passwordData)
      
      // 模拟API响应
      if (passwordData.currentPassword === '123456') { // 模拟验证当前密码
        ElMessage.success('密码修改成功')
        return true
      } else {
        throw new Error('当前密码不正确')
      }
    } catch (error) {
      ElMessage.error(error.message || '密码修改失败')
      return false
    }
  }

  // 退出
  const logout = () => {
    _clearAuth()
    ElMessage.success('已退出登录')
  }

  return { 
    token, 
    userInfo, 
    isLoggedIn, 
    login, 
    register, 
    logout, 
    updateProfile, 
    changePassword 
  }
})